package com.ys.controller.api.storage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.amazonorder.TpAmazonShopOrderDaily;
import com.ys.entity.storage.TccAssembleItem;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.storage.TccAssembleService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tccAssemble")
public class ApiInterTccAssembleController {
	
	private static final Logger logger = Logger.getLogger(ApiInterTccAssembleController.class);
	
	@Autowired
	private TccAssembleService tccAssembleService;
	
	@Autowired
	private CommonApiService<TccAssembleItem> commonApiService;

	@RequiresPermissions("TccAssemble:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TccAssembleItem cond){
		
        cond = setSeachSql(cond);
		
		LayuiTableVoJA vo = commonApiService.searchLay(cond);
		return vo;
	}

    /**
     * 设置查询的cond的sql设置
     */
    private TccAssembleItem setSeachSql(TccAssembleItem cond){
        cond.setStatus(1);//数据过滤
        
        cond.addLeftJoin("TCC_Assemble B ON B.Bid = A.Pbid")
        .addField("B.Bid bid")
        .addField("B.ParentAssembleNumber parentAssembleNumber")
        .addField("B.ParentSinglePrice parentSinglePrice")
        .addField("B.AuditTime auditTime")
        .addField("B.State state")
        
        .addLeftJoin("TCC_StockControl BBBB ON BBBB.Id = A.StockControlId")
        .addField("BBBB.GDepot vck")
        .addField("BBBB.Vkq vkq")
        .addField("BBBB.Vhw vhw")
        .addField("BBBB.PurchasePrice subBomPrice")
        
        .addLeftJoin("TCG_PurchaseInStorage C ON C.Id = A.PurchaseStorageId")
        .addField("C.PurchaseContractBid bidConstract")
        .addField("C.Bid bidInStorage")
        
        .addLeftJoin("TCW_PartnerBankInfo BBB ON BBB.Id = C.PartnerBankInfoId")
        .addField("BBB.PartnerName supplyCompanyVname")
        
        .addLeftJoin("TCG_PurchaseAppointOrderItem BB ON BB.Id = B.AppointOrderItemId")
        .addField("BB.ProductCode productCode")
        .addField("BB.ProductName productName")
        .addField("BB.CodeMerge codeMerge")
        .addField("BB.ReserveNumber parentPurchaseNumber")
        
        .addLeftJoin("TCG_PurchaseAppointOrder D ON D.Id = B.AppointOrderId")
        .addField("D.Bid bidAppointOrder")

        .addLeftJoin("TB_CompanyInfo E ON E.Vid = B.CompanyVid")
        .addField("E.Vid companyVid")
        .addField("E.Vname companyVname")

        .addLeftJoin("THR_OperateCompanyApply F ON F.Vgsbm = B.Vgsbm")
        .addField("F.Vgsbm vgsbm")
        .addField("F.Vgsjc vgsjc")

        .addLeftJoin("TCG_PurchaseContract G ON G.Id = A.ConstractId")
        .addField("G.Bid bidConstract")
        
        .addLeftJoin("TCG_PurchaseAppointOrderProductComponent H ON H.Id = A.AppointOrderComponentId")
        .addField("H.SubCode subCode")
        .addField("H.SubName subName")
        .addField("H.SubCodeMerge subCodeMerge")
        .addField("H.SubBomNumber subBomNumber")
        .addField("(B.ParentAssembleNumber * H.SubBomNumber) subRealUsedNum")
        .addField("(A.SubPlanStorageNum - A.SubRealStorageNum) subAssembleLostNum")
        
        .addLeftJoin("TCC_StockControl J ON J.Id = A.StockControlId")
        .addField("J.GDepot vcq")
        .addField("J.Vkq vkq")
        .addField("J.Vhw vhw")
        ;
		
		//权限
		cond = commonApiService.dataAuth(MenuId.TCC_Assemble, cond);
        return  cond;
    }
	
	/**
	 * 正常组装
	 */
	@RequiresPermissions("tccAssemble:batchPass")
	@PostMapping("/batchPass")
    @ResponseBody
	public R batchPass(String bids) {
		
		logger.info("批量通过正常组装bids---" + bids);
		if (bids == null || bids.length() == 0) {
			return R.error("单号有误");
		}
		try {
			List<String> listBid = new ArrayList<String>();
			for(String bid : bids.split(",")) {
				if (listBid.contains(bid)) {
					continue;
				} else {
					listBid.add(bid);
					tccAssembleService.pass(bid);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return R.ok("操作成功");
	}
	
	/**
	 * 异常组装
	 */
	@RequiresPermissions("tccAssemble:exception")
	@PostMapping("/doError")
    @ResponseBody
	public R doError(HttpServletRequest request,
			String bid, Integer parentAssembleNumber, String subData) throws Exception{
		
		logger.info("bid---" + bid);
		logger.info("subData---" + subData);
		
		try {
			return tccAssembleService.doError(bid, parentAssembleNumber, subData);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("数据出错，请联系客服处理");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("tccAssemble:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccAssembleItem cond, String conditions) throws Exception{
		
        cond = setSeachSql(cond);
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCC_Assemble)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<TpAmazonShopOrderDaily> util = new ExportExcelUtils<TpAmazonShopOrderDaily>(new TpAmazonShopOrderDaily());
        
        String toFilePath = util.exportExcel(listData, listField, "预约调拨单");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }
}
